import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { Picker, Card } from '@ant-design/react-native';
import FontAwesome from '@expo/vector-icons/FontAwesome';
import { getDevices } from '../../../api/device';
import { deviceTypeEnToZhMap } from '@/constants/deviceParameters';

interface SelectDeviceCardProps {
  onDeviceSelect: (deviceId: string) => void;
}

const SelectDeviceCard: React.FC<SelectDeviceCardProps> = ({ onDeviceSelect }) => {
  const [visible, setVisible] = useState(false);
  const [deviceData, setDeviceData] = useState<{ value: string; label: string }[]>([]);

  useEffect(() => {
    // 获取设备列表
    getDevices().then(res => {
      const devices = res.data.data.devices || [];
      setDeviceData(
        devices.map((dev: any) => ({
          value: String(dev.id),
          label: `${dev.name}（${deviceTypeEnToZhMap[dev.type] || dev.type}）`,
        }))
      );
    });
  }, []);

  const handleOk = (value: any) => {
    if (value && value[0]) {
      onDeviceSelect(value[0]);
    }
    setVisible(false);
  };

  return (
    <>
      <TouchableOpacity onPress={() => setVisible(true)} activeOpacity={0.7}>
        <Card style={styles.card}>
          <View style={styles.iconWrapper}>
            <FontAwesome name="list" size={60} color="#888" />
            <Text style={{ marginTop: 10, color: '#888' }}>将已有设备添加至场景</Text>
          </View>
        </Card>
      </TouchableOpacity>
      <Picker
        data={deviceData}
        cols={1}
        visible={visible}
        onOk={handleOk}
        onDismiss={() => setVisible(false)}
        title="请选择设备"
      />
    </>
  );
};

const styles = StyleSheet.create({
  card: {
    width: 160,
    height: 160,
    borderRadius: 20,
    overflow: 'hidden',
    elevation: 2,
    backgroundColor: '#fff',
    alignSelf: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  iconWrapper: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default SelectDeviceCard;